<template>
  <div class="zd-community">
    <!-- 查询区域 -->
    <el-form ref="form" :model="searchData" label-width="120px" class="clearfix">
      <el-form-item label="所在地区" class="pull-left item-right" style="width:180px">
          <el-select v-model="searchData.districtNo" placeholder="请选择"  clearable style="width:120px">
              <el-option
                      v-for="item in optionDiq"
                      :key="item.DistrictName"
                      :label="item.DistrictName"
                      :value="item.DistrictNo">
              </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="社区名称" class="pull-left" label-width="160px">
        <el-input v-model="searchData.cName" placeholder="请输入社区名称">
        </el-input>
      </el-form-item>
      <el-form-item label="分组" class="pull-left" label-width="80px">
        <el-select v-model="searchData.cGroup" placeholder="请选择分组">
          <el-option label="全部" value="0"></el-option>
          <el-option label="A" value="1"></el-option>
          <el-option label="B" value="2"></el-option>
        </el-select>
      </el-form-item>
      <!-- 操作区域 -->
      <div class="pull-right">
        <el-button @click="searchHandler" class=" pd-bt">查询</el-button>
        <el-button type="primary" @click="queryHandler" class=" pd-bt">添加</el-button>
      </div>
    </el-form>

    <!---->
    <template>
      <el-table  :data="tableData" border empty-text="当前列表为空" v-loading="loading" element-loading-text="加载中" style="width: 100%">
        <!-- <el-table-column align="center" label="序号" width="70">
          <template slot-scope="scope">
            {{scope.$index+1}}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="cscode" label="社区编号" min-width="200">
        </el-table-column> -->
        <el-table-column prop="DistrictFullName" label="所在地区" align="center" min-width="200">
        </el-table-column>
        <el-table-column prop="CName" label="社区名称" align="center" min-width="200">
        </el-table-column>
        
        <el-table-column prop="CGroup" :formatter="groupFormatter" label="分组" align="center" min-width="200">
        </el-table-column>
        <el-table-column min-width="100" align="center" label="操作">
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="queryHandler(scope.$index, scope.row)">查看</el-button>
            <el-button size="small" type="text" @click="deleteHandler(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!--分页-->
    <div class="block mg-20-auto ">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="pageCount" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 编辑查看对话框 -->
    <el-dialog :title="dialogTitle" v-loading="saveloading" element-loading-text="正在保存" :visible.sync="centerDialogVisible" width="50%" :close-on-click-modal="false">

      <el-form :model="form" :rules="formRules" ref="communityForm">
        <el-form-item label="社区名称" :label-width="formLabelWidth" prop="CName">
          <el-input v-model="form.CName" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="所在地区" :label-width="formLabelWidth">
          <el-cascader :clearable="true" class="zd-community-cascader" v-model="form.DistrictFullNo" :change-on-select="false" @active-item-change="handleItemChange" :options="options">
          </el-cascader>
        </el-form-item>
        <el-form-item label="分组" :label-width="formLabelWidth">
          <el-select class="zd-community-group" v-model="form.CGroup" placeholder="请选择分组">
            <el-option label="A" value="1"></el-option>
            <!-- 干预组用A表示，对照组用B表示 -->
            <el-option label="B" value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveHandler">保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "community1",
  data() {
    return {
      searchData: {
        cName: "",
        cGroup: "0",
        districtNo:''
      },
      dialogTitle: "",
      parentDistrictNo: "",
      maxHeight:'',
       optionDiq:[],
      form: {
        CName: "",
        DistrictFullNo: []
      },
      groupFormatter(row, column, cellValue, index) {
        // 干预组用A表示，对照组用B表示
        return cellValue ? (cellValue == 1 ? "A" : "B") : "";
      },
      formRules: {
        CName: [{ required: true, message: "请填写社区名称", trigger: "blur" }]
      },
      centerDialogVisible: false,
      formLabelWidth: "120px",
      total: null,
      pageSize: 10,
      pageCount: 1,
      loading: false,
      saveloading: false,
      tableData: [],
      options: [],
      currentValue: "",
      item: null,
      tmpValue: "",
      currentLevel: 1,
      DistrictFullName: [],
      currentLabel: ""
    };
  },
  mounted() {},
  beforeMount:function() {
    let that=this;
    let appHeight=$(window).height();
    let autoheight=(appHeight-260)+'px'
    that.maxHeight=autoheight
  },
  methods: {
    handleItemChange(value, callback) {
      this.handleChange(value, callback);
    },
    handleChange(value, callback) {
      this.currentValue = value;
      this.tmpValue = value[0];
      this.parentDistrictNo = value[value.length - 1];
      if (value.length == 1) {
        this.item = this.options.find(this.findItem);
      } else if (value.length == 2) {
        let tmpItem = this.options.find(this.findItem);
        this.tmpValue = value[1];
        this.item = tmpItem.children.find(this.findItem);
      } else if (value.length == 3) {
        let tmpItem = this.options.find(this.findItem);
        this.tmpValue = value[1];
        let item = tmpItem.children.find(this.findItem);
        this.tmpValue = value[2];

        this.item = item.children.find(this.findItem);
      }

      this.DistrictFullName[value.length - 1] = this.item.label;

      if (value.length >= 3) {
        return false;
      }

      this.getDistricts(2, this.item, callback);
    },
    findItem(value) {
      return this.tmpValue == value.DistrictNo;
    },
    findValueByLabel(option) {
      return this.currentLabel == option.DistrictName;
    },
    setDefaultValue(nameArray, DistrictFullNo) {
      // 获取省市的编码
      let provinceNo = DistrictFullNo.substring(0, 2);
      let cityNo = DistrictFullNo.substring(0, 4);
      // 获取当前的Label
      this.currentLabel = nameArray[0];
      this.tmpValue = provinceNo;
      // 获取省的item
      let disNo1 = this.options.find(this.findItem);

      let provinceArr = new Array(provinceNo);

      let valueArr = new Array(disNo1.value);
      let cityArr = new Array(provinceNo, cityNo);

      // this.parentDistrictNo = disNo1.value;

      let getCitys = () => {
        // setTimeout(() => {
        this.handleChange(cityArr);
        // }, 0);
      };

      this.handleChange(provinceArr, getCitys);
      this.form.DistrictFullNo = new Array(provinceNo, cityNo, DistrictFullNo);
    },
    queryHandler(index, row) {
      if (row) {
        this.dialogTitle = "查看社区";
        this.form = JSON.parse(JSON.stringify(row));

        if (row.DistrictFullName && row.DistrictNo) {
          this.form.DistrictFullName = row.DistrictFullName
            ? row.DistrictFullName.split(" ")
            : [];

          this.setDefaultValue(row.DistrictFullName.split(" "), row.DistrictNo);
        }
      } else {
        this.dialogTitle = "添加社区";
        this.form = {};
        this.$nextTick(() => {
          this.$refs.communityForm.resetFields();
        });
      }
      this.centerDialogVisible = true;
    },
    deleteHandler(index, row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let that = this;
          that
            .service({
              url: "Dic/DeleteCommunity?sysId=" + row.SYS_ID,
              method: "post"
            })
            .then(resp => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });

              that.getList();
              // that.tableData.push(that.form);
            })
            .catch(data => {
              that.loading = false;
            });
        })
        .catch(() => {});
    },
    handleSizeChange(val) {
      //条数改变
      this.pageSize = val;
      this.getList();
    },
    GetCommunityDistrict:function(){    //获取社区行政区
            let that = this;
            that.service({
                url: "/Dic/GetCommunityDistrict",
                method: "get",
                params: {
                }
            }).then(response => {
                that.optionDiq=response.dtData;
            })
            .catch(data => {

            });
        },
    handleCurrentChange(val) {
      //页数改变
      this.pageCount = val;
      this.getList();
    },
    getDistricts(type, item, callback) {
      let that = this;
      let parentDistrictNo = that.parentDistrictNo;
      that
        .service({
          url: "dic/GetDistrict?parentDistrictNo=" + that.parentDistrictNo,
          method: "get",
          params: {}
        })
        .then(resp => {
          let tmpArr = [];

          if (!resp.dtData || resp.dtData.length <= 0) {
            return;
          }

          let children = [];

          if (that.currentValue.length >= 2) {
            children = null;
          }

          resp.dtData.forEach(pic => {
            pic.value = pic.DistrictNo;
            pic.label = pic.DistrictName;
            pic.children = children;
            tmpArr.push(pic);
          });

          if (type == 1) {
            that.options = tmpArr;
          } else if (type == 2) {
            // that.$set(item, "children", tmpArr);
            item.children = tmpArr;
          } else if (type == 3) {
            return tmpArr;
          }

          if (callback) {
            callback();
          }
        })
        .catch(data => {
          console.log(data);
          that.loading = false;
        });
    },
    getList() {
      let that = this;
      this.loading = true;
      // 默认选项为0排除掉
      let searchDataGroup =
        that.searchData.cGroup == 0 ? "" : that.searchData.cGroup;
      that
        .service({
          url: "dic/GetCommunity",
          method: "get",
          params: {
            pageCount: that.pageCount - 1,
            pageSize: that.pageSize,
            ...that.searchData,

            cGroup: searchDataGroup
          }
        })
        .then(resp => {
          that.tableData = resp.dtData;
          that.total = parseInt(resp.dtData[0].TotalCount);
          that.loading = false;
        })
        .catch(data => {
          that.loading = false;
        });
    },
    searchHandler() {
      this.pageCount = 1; // 分页索引
      this.getList();
    },
    saveHandler() {
      let _this = this;
      this.$refs.communityForm.validate(valid => {
        if (valid) {
          if (
            _this.form.DistrictFullNo &&
            _this.form.DistrictFullNo.length > 0
          ) {
            _this.tmpValue = _this.form.DistrictFullNo[2];
            let item = _this.item.children.find(_this.findItem);
            _this.DistrictFullName[2] = item.label;

            _this.form.DistrictFullName = _this.DistrictFullName.join(" ");

            _this.form.DistrictNo = _this.form.DistrictFullNo[2];
          }

          _this.saveloading = true;
          _this
            .service({
              url: "Dic/SaveCommunity",
              method: "post",
              data: {
                ..._this.form
              }
            })
            .then(resp => {
              _this.getList();
              _this.centerDialogVisible = false;
              _this.saveloading = false;
            })
            .catch(data => {
              _this.getList();
              _this.loading = false;
              _this.saveloading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
  },
  mounted() {
    this.getList();
    this.getDistricts(1);
    this.GetCommunityDistrict()
  },
  components: {}
};
</script>
<style lang="scss">
.zd-community {
}

.zd-community .el-dialog__wrapper .el-dialog .el-dialog__footer {
  text-align: center;
}
.zd-community-cascader,
.zd-community-group {
  width: 100%;
}
</style>